/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.gadgets.discussions.client;

import com.gadglet.client.gwt.GadgetNativeUtils;
import com.gadglet.client.gwt.core.GadgletQuery;
import com.gadglet.client.gwt.core.GadgletRequest;
import com.gadglet.client.gwt.core.GadgletResponse;
import com.gadglet.client.gwt.core.ui.ShareWithDialogPanel;
import com.gadglet.client.gwt.ui.ActionLabel;
import com.gadglet.client.gwt.ui.CanvasViewMainPanel;
import com.gadglet.client.gwt.ui.ContentText;
import com.gadglet.client.gwt.ui.DebugDialogBox;
import com.gadglet.client.gwt.ui.SimpleDialogBox;
import com.gadglet.client.gwt.ui.UIUtils;
import com.gadglet.gadgets.discussions.shared.Params;
import com.gadglet.params.ProfileFields;
import com.gadglet.params.ReqActionTypes;
import com.gadglet.params.ReqTypes;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.gadgets.client.ContentSection;
import com.google.gwt.gadgets.client.Gadget.ContentType;
import com.google.gwt.gadgets.client.Gadget.InjectContent;
import com.google.gwt.gadgets.client.PreferencesFeature;
import com.google.gwt.gadgets.client.PreferencesProvider;
import com.google.gwt.gadgets.client.io.MethodType;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;


@InjectContent(files = "canvas.html")
@ContentType(type = "html", views = { "canvas" })
public class DiscussionsCanvasView extends ContentSection<DiscussionsGadget> {
	private DebugDialogBox debug = null;

	/**
	 * Query object use to create a request for personal notes.
	 * ReqTypes.BIZLET_SIGNED will generate url to the domainSignedRequest
	 * servlet
	 */
	final GadgletQuery viewDiscussionsQry = new GadgletQuery(
			ReqTypes.BIZLET_SIGNED);

	/**
	 * a query to view all replays to a discussion
	 */
	final GadgletQuery viewDiscussionsReplyQry = new GadgletQuery(
			ReqTypes.BIZLET_SIGNED);
	
	
	final GadgletQuery chcangeDiscussionsReplyQry= new GadgletQuery(
			ReqTypes.BIZLET_SIGNED);
	
	final ChangeDiscussionsReplys changeDiscussionsReplys = new ChangeDiscussionsReplys(chcangeDiscussionsReplyQry);

	
	
	final ViewDiscussionReplys viewDiscussionReplys = new ViewDiscussionReplys(
			viewDiscussionsReplyQry);

	/**
	 * Request object used to send a request to the gadget server and process
	 * the results
	 */
	final ViewDiscussions viewDiscussionsRequest = new ViewDiscussions(
			viewDiscussionsQry);

	/**
	 * Query object used to build "add", "update" and "delete" requests
	 */

	final GadgletQuery changeDiscussionsQry = new GadgletQuery(
			ReqTypes.BIZLET_SIGNED);

	/**
	 * Request Object used to perform "add" and "delete" requests and process
	 * the results
	 */

	final GadgletRequest addDeleteDiscussions = new ChangeDiscussions(
			changeDiscussionsQry);

	/**
	 * Request Object used to perform "update" requests
	 */

	final GadgletRequest changeDiscussionsRequest = new UpdateDiscussions(
			changeDiscussionsQry);
	
	

	final Grid results = new Grid();
	final GadgetState gadgetState = new GadgetState();
	protected final HorizontalPanel paging = new HorizontalPanel();

	final Button prevButton = new Button();
	final Button nextButton = new Button();
	final PreferencesFeature  prefsUtils = PreferencesProvider.get();

	final SimpleDialogBox serverMessage = SimpleDialogBox
			.getMesseageDialogBox();
	
	final ActionLabel viewAll = new ActionLabel(
			prefsUtils.getMsg("gadgetLabelView")+" "+prefsUtils.getMsg("gadgetLabelAll") );
	
	final int discussionsNum = 20;
	@Override
	public void init(DiscussionsGadget gadget) {
		
		changeDiscussionsReplys.setMethodType(MethodType.POST);
		
		
		viewAll.setVisible(false);
		
		viewAll.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				// / view replay ....

				gadgetState.clear();
				viewAll.mouseOff();
						
				try {
					GadgetNativeUtils.setTitle(prefsUtils.getMsg("gadgetTitleDiscussions"));
				} catch (Exception e) {

				}
				
				viewDiscussionsQry.setStartItemsFrom(0);
				viewDiscussionsQry.setItemsNum(discussionsNum);
				viewDiscussionsRequest.makeRequest();
				

			}

		});
		
		

		results.setCellSpacing(0);
		results.setCellPadding(10);

		addDeleteDiscussions.setMethodType(MethodType.POST);

		debug = DebugDialogBox.getErrorNotifier();

		prevButton.setText(prefsUtils.getMsg("gadgetLabelPrevious"));
		nextButton.setText(prefsUtils.getMsg("gadgetLabelNext"));

		try {

			gadgetState.setDiscussionId(GadgetNativeUtils
					.getNavigateToCanvasParam(Params.DISCUSSION_ID
							.getParamName()));
			if (gadgetState.getDiscussionId() != null) {
				gadgetState.setSingleDiscussion(true);
				gadgetState.setDiscussionTitle(GadgetNativeUtils
						.getNavigateToCanvasParam(Params.DISCUSSION_TEXT
								.getParamName()));

			}

		} catch (Exception e) {

			debug.showError(7, e.toString());

		}

		final CanvasViewMainPanel mainPanel = new CanvasViewMainPanel();

		final HorizontalPanel addItemPanel = new HorizontalPanel();
		final DisclosurePanel addDisclosurePanel = new DisclosurePanel();

		ActionLabel add = new ActionLabel(prefsUtils.getMsg("gadgetLabelNew"));
		add.setTitle(prefsUtils.getMsg("gadgetLabelNew"));

		addDisclosurePanel.setHeader(add);

		final VerticalPanel bookMark = new VerticalPanel();

		final TextArea discssionText = new TextArea();
		discssionText.setWidth("400px");

		bookMark.add(discssionText);

		final Button saveButton = new Button(
				prefsUtils.getMsg("gadgetLabelSave"));

		addItemPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_BOTTOM);
		addItemPanel.add(bookMark);

		addItemPanel.add(new HTML("&nbsp;"));
		addItemPanel.add(saveButton);

		addDisclosurePanel.add(addItemPanel);

		mainPanel.add(addDisclosurePanel);
		
		mainPanel.add(viewAll);

		mainPanel.add(results);

		RootPanel.get().add(mainPanel.getGadgetPanel());

		saveButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				changeDiscussionsQry.setRequestAction(ReqActionTypes.ADD);
				changeDiscussionsQry.clearParamList();

				changeDiscussionsQry.addParam(
						Params.DISCUSSION_TEXT.getParamName(),
						discssionText.getValue());

				addDeleteDiscussions.makeRequest();
				discssionText.setValue("");

			}
		});

		prevButton.setVisible(false);
		prevButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				viewDiscussionsQry.setStartItemsFrom(viewDiscussionsQry
						.getStartFrom() - viewDiscussionsQry.getItemNum());
				viewDiscussionsRequest.makeRequest();

			}

		});
		paging.add(prevButton);

		nextButton.setVisible(false);
		nextButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				viewDiscussionsQry.setStartItemsFrom(viewDiscussionsQry
						.getStartFrom() + viewDiscussionsQry.getItemNum());
				viewDiscussionsRequest.makeRequest();

			}

		});
		paging.add(nextButton);

		viewDiscussionsQry.setRequestAction(ReqActionTypes.VIEW);
		viewDiscussionsQry.setStartItemsFrom(0);
		viewDiscussionsQry.setItemsNum(discussionsNum);

		viewDiscussionsReplyQry.setRequestAction(ReqActionTypes.VIEW);
		viewDiscussionsReplyQry.setRequestItemkey(gadgetState.getDiscussionId());
		viewDiscussionsReplyQry.setCustomtContentName("replay");
		
		
		if (gadgetState.isSingleDiscussion()) {
			
			viewDiscussionReplys.makeRequest();
		} else {
		
			viewDiscussionsRequest.makeRequest();
		}

		
		

	}

	public class ViewDiscussions extends GadgletRequest {
		GadgletResponse jResponse;

		ViewDiscussions(GadgletQuery req) {
			super(req);

		}

		@Override
		protected void processResults(GadgletResponse data) {
			jResponse = data;

			results.resize(0, 4);
			results.clear();

			if (jResponse.isSuccessful() && jResponse.getRootItemsNum() > 0) {
				
				viewAll.setVisible(false);
				results.resize(1, 4);

				int index;

				for (index = 0; index < jResponse.getRootItemsNum(); index++) {

					final ContentText text = new ContentText(
							data.getStringItemValue(
									Params.DISCUSSION_TEXT.getParamName(),
									index));

					final String discussionId = jResponse
							.getItemKeyValue(index);

					VerticalPanel discussionItem = new VerticalPanel();
					discussionItem.add(text);

					final ActionLabel view = new ActionLabel(
							prefsUtils.getMsg("gadgetLabelView"));

					view.setTitle(prefsUtils.getMsg("gadgetLabelView"));

					view.addClickHandler(new ClickHandler() {
						@Override
						public void onClick(ClickEvent event) {
							// / view replay ....

							gadgetState.setDiscussionId(discussionId);
							gadgetState.setSingleDiscussion(true);
							gadgetState.setDiscussionTitle(text.getText());

							viewDiscussionsReplyQry
									.setRequestItemkey(gadgetState
											.getDiscussionId());
							viewDiscussionsReplyQry
									.setCustomtContentName("replay");
							viewDiscussionReplys.makeRequest();

						}

					});

					results.setWidget(index, 0, discussionItem);
					results.setWidget(index, 1, view);

					final ActionLabel deleteLabel = new ActionLabel(
							prefsUtils.getMsg("gadgetLabelDelete"));

					deleteLabel.setItemId(jResponse.getItemKeyValue(index));

					if (data.isDeletePermitted(index)) {

						deleteLabel.addClickHandler(new ClickHandler() {
							@Override
							public void onClick(ClickEvent event) {
								changeDiscussionsQry.clearParamList();
								changeDiscussionsQry
										.setRequestAction(ReqActionTypes.DELETE);
								changeDiscussionsQry
										.setRequestItemkey(discussionId);
								addDeleteDiscussions.makeRequest();

							}

						});

					} else {
						// delete: "hide" sharing

						deleteLabel.addClickHandler(new ClickHandler() {
							@Override
							public void onClick(ClickEvent event) {
								deleteLabel.mouseOff();
								changeDiscussionsQry.clearParamList();

								changeDiscussionsQry
										.setRequestAction(ReqActionTypes.DELETE);
								changeDiscussionsQry
										.setCustomtContentName("sharing");
								changeDiscussionsQry
										.setRequestItemkey(discussionId);
								addDeleteDiscussions.makeRequest();
								changeDiscussionsQry
										.setCustomtContentName(null);

							}

						});
					}

					results.setWidget(index, 2, deleteLabel);

					if (data.isSharePermitted(index)) {

						final ActionLabel shareWithLabel = new ActionLabel(
								prefsUtils.getMsg("gadgetLabelShare"));

						shareWithLabel.addClickHandler(new ClickHandler() {

							public void onClick(ClickEvent event) {
								shareWithLabel.mouseOff();
								ShareWithDialogPanel panel = ShareWithDialogPanel
										.getShareWithDialogPanel();
								panel.showShareWithDialogPanel(discussionId,
										text.getText());

							}

						});

						results.setWidget(index, 3, shareWithLabel);
					} else {
						String nick = data.getStringItemValue(
								ProfileFields.PROFILE_NICKNAME.getParamName(),
								index);
						String photo = data.getStringItemValue(
								ProfileFields.PROFILE_THUMBNAILURL
										.getParamName(), index);

						HorizontalPanel profile = new HorizontalPanel();
						profile.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
						if (nick != null)
							if (nick != null) {
								profile.add(new HTML(prefsUtils
										.getMsg("gadgetLabelSharedBy") + ":"));
								profile.add(UIUtils.getSpace());
								profile.add(new Label(nick));

							}
						if (photo != null && !photo.isEmpty()) {
							profile.add(UIUtils.getSpace());
							Image photoImg = new Image(photo);
							photoImg.setPixelSize(40, 40);
							profile.add(photoImg);

						}

						results.setWidget(index, 3, profile);

					}

					results.resize(index + 3, 4);

				}

				if (viewDiscussionsQry.getStartFrom() > 0)
					prevButton.setVisible(true);
				else
					prevButton.setVisible(false);

				if (jResponse.hasMoreItems())
					nextButton.setVisible(true);
				else
					nextButton.setVisible(false);

				results.setWidget(index, 0, paging);

			}

		}
	}

	
	
	public class ViewDiscussionReplys extends GadgletRequest {
	

		ViewDiscussionReplys(GadgletQuery req) {
			super(req);

		}

		@Override
		protected void processResults(GadgletResponse data) {
			
			results.resize(0, 4);
			results.clear();
			viewAll.setVisible(true);

			if (data.isSuccessful() && data.getRootItemsNum() > 0) {
				results.resize(1, 4);

				int index;
			

				for (index = 0; index < data.getRootItemsNum(); index++) {

					final ContentText replayText = new ContentText(
							data.getStringItemValue(
									Params.DISCUSSION_TEXT.getParamName(),
									index));

					final String noteId = data.getItemKeyValue(index);
					
					HorizontalPanel replayItem = new HorizontalPanel();
				
					VerticalPanel discussionItem = new VerticalPanel();
					
					String creation = data.getStringItemValue(Params.DISCUSSION_MSD_DATE.getParamName(), index);
					HTML replyDate = new HTML(creation);
					
					replyDate.setStyleName("gadglet-DateTimeLabel");
					if(creation!=null)
						discussionItem.add(replyDate);
					
					discussionItem.add(replayText);

					final TextArea discussionReplay = new TextArea();

					final Button saveReplay = new Button(
							prefsUtils.getMsg("gadgetLabelSave"));
					
					replayItem.setSpacing(3);
					 
					 int messageLevel = 0;
					 
					 try {
						messageLevel = Integer.parseInt(data.getStringItemValue(Params.DISCUSSION_LEVEL.getParamName(), index));
					} catch (NumberFormatException e) {
					
					}
			
									
					replayItem.add(UIUtils.getSpaces(messageLevel*4));

					String nick = data.getStringItemValue(
							ProfileFields.PROFILE_NICKNAME.getParamName(),
							index);
					
					String title = data.getStringItemValue(
							ProfileFields.PROFILE_TITLE.getParamName(),
							index);
					
					VerticalPanel details = new VerticalPanel();
					details.setWidth("100px");
										
					details.add(new HTML(nick));
					
					details.add(new HTML(title));
					
					replayItem.add(details);
					
					replayItem.add(discussionItem);
							

					results.setWidget(index, 0, replayItem);
					
					saveReplay.setVisible(false);

					if (data.isUpdatePermitted(index)) {
						
						final ActionLabel replay = new ActionLabel(
								prefsUtils.getMsg("gadgetLabelReply"));

						replay.setTitle(prefsUtils.getMsg("gadgetLabelEdit"));

						replay.addClickHandler(new ClickHandler() {
							@Override
							public void onClick(ClickEvent event) {
								replay.mouseOff();
								
								discussionReplay.setVisible(true);
								saveReplay.setVisible(true);

							}

						});
						
						
						replayItem.add(replay);
						
						replayItem.setCellVerticalAlignment(replay,HasVerticalAlignment.ALIGN_BOTTOM );
						
						discussionReplay.setWidth("700px");
						discussionReplay.setVisible(false);
						
						discussionItem.add(discussionReplay);
						discussionItem.add(saveReplay);

						saveReplay.addClickHandler(new ClickHandler() {
							@Override
							public void onClick(ClickEvent event) {
								// ignore empty
								if (discussionReplay.getText().length() == 0) {
									discussionReplay.setVisible(false);
									saveReplay.setVisible(false);

								} else {
								

									chcangeDiscussionsReplyQry.clearParamList();
																	

									chcangeDiscussionsReplyQry
											.setRequestAction(ReqActionTypes.ADD);
									
									chcangeDiscussionsReplyQry
									.setRequestItemkey(gadgetState.getDiscussionId());

									chcangeDiscussionsReplyQry.addParam(
											Params.DISCUSSION_PARENT_ID
													.getParamName(), noteId);

									chcangeDiscussionsReplyQry.addParam(
											Params.DICUSSION_REPLY
													.getParamName(),
											discussionReplay.getText());

									chcangeDiscussionsReplyQry
											.setCustomtContentName("replay");
									changeDiscussionsReplys.makeRequest();
								}

							}
						});

					}

							
					 
				
				//	results.setWidget(index, 1, replay);
					
					results.resize(index + 3, 4);
		
				}
			}

		}
	}

	
	public class ChangeDiscussionsReplys extends GadgletRequest {
		ChangeDiscussionsReplys(GadgletQuery req) {
			super(req);
		}

		@Override
		protected void processResults(GadgletResponse data) {
			GadgletResponse jResponse = data;

			if (jResponse.isSuccessful()) {
				// reffresh
				viewDiscussionReplys.makeRequest();
			} else {

				serverMessage
						.showError(prefsUtils.getMsg(jResponse.getError()));
			}

		}
	}
	
	public class ChangeDiscussions extends GadgletRequest {
		ChangeDiscussions(GadgletQuery req) {
			super(req);
		}

		@Override
		protected void processResults(GadgletResponse data) {
			GadgletResponse jResponse = data;

			if (jResponse.isSuccessful()) {
				// reffresh
				viewDiscussionsRequest.makeRequest();
			} else {

				serverMessage
						.showError(prefsUtils.getMsg(jResponse.getError()));
			}

		}
	}

	public class UpdateDiscussions extends GadgletRequest {
		UpdateDiscussions(GadgletQuery req) {
			super(req);
		}

		@Override
		protected void processResults(GadgletResponse data) {

			GadgletResponse jResponse = data;

			if (jResponse.isSuccessful()) {
				// do nothing
			} else {

				serverMessage
						.showError(prefsUtils.getMsg(jResponse.getError()));
			}

		}
	}

	
	public class GadgetState {

		private boolean singleDiscussion;

		private String discussionId;

		private String discussionTitle;

		public boolean isSingleDiscussion() {
			return singleDiscussion;
		}

		public void setSingleDiscussion(boolean singleDiscussion) {
			this.singleDiscussion = singleDiscussion;
		}

		public String getDiscussionId() {
			return discussionId;
		}

		public void setDiscussionId(String discussionId) {
			this.discussionId = discussionId;
		}

		public void clear() {
			this.discussionId = null;
			this.singleDiscussion = false;
			discussionTitle = null;

		}

		public String getDiscussionTitle() {
			return discussionTitle;
		}

		public void setDiscussionTitle(String discussionTitle) {
			
			
			this.discussionTitle = discussionTitle;
			String title = "";
			if (this.discussionTitle != null
					&& this.discussionTitle.length() > 100)
				title = this.discussionTitle.substring(0, 100);
			else
				title = this.discussionTitle;

			try {
				GadgetNativeUtils.setTitle(title);
			} catch (Exception e) {

			}

		}

	}

}
